package 基础篇.线程池.ForkJoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/7/29 0029.
 */
public class PrintTask extends RecursiveAction {
    private static final int THRESHOLD=50;
    private int start;
    private int end;
    public PrintTask(int start,int end){
        this.start=start;
        this.end=end;
    }
    @Override
    protected void compute() {
        if(end-start<THRESHOLD){
            System.out.println(Thread.currentThread().getName()+"范围 start:"+start+" end:"+end);
            for(int i=start;i<end;i++){
                System.out.println(Thread.currentThread().getName()+" "+i);
            }
        }else{
            int middle=(start+end)/2;
            PrintTask left=new PrintTask(start,middle);
            PrintTask right=new PrintTask(middle,end);
            left.fork();
            right.fork();
        }
    }
}

class ForkJoinPoolTest{
    public static void main(String[] args) throws InterruptedException {
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        PrintTask printTask=new PrintTask(0,1000);
        forkJoinPool.submit(printTask);
        forkJoinPool.awaitTermination(2, TimeUnit.SECONDS);
        forkJoinPool.shutdown();
    }
}